package org.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        nativeQuery(em,"SHOW TABLES");
        nativeQuery(em,"SHOW COLUMNS FROM CUSTOMER");
        nativeQuery(em,"SHOW COLUMNS FROM ORDERITEM");
        nativeQuery(em,"SHOW COLUMNS FROM CUSTOMER_ORDERITEM");
        persistCustomer(em);
        persistOrderItem(em);
        nativeQuery(em,"SELECT * FROM CUSTOMER");
        nativeQuery(em,"SELECT * FROM ORDERITEM");
        nativeQuery(em,"SELECT * FROM CUSTOMER_ORDERITEM");
        em.close();
        emf.close();
    }
    private static void persistOrderItem(EntityManager em){
        OrderItem orderItem = new OrderItem();
        orderItem.setItemName("QK USB Driver");
        orderItem.setQuantity(5);

        Customer customer = new Customer();
        customer.setName("Heather Harton");
        customer.setAddress("563 Holbein Square, Woodbine");
        customer.addOrderItem(orderItem);
        em.getTransaction().begin();
        em.merge(orderItem);
        em.getTransaction().commit();
    }
    private static void persistCustomer(EntityManager em){
        Customer customer = new Customer();
        customer.setName("Maria Dorsey");
        customer.setAddress("1719 sumarker Boulevard Sylvania");
        customer.addOrderItem("GEN SSD",2);
        customer.addOrderItem("SK Monitor",3);
        em.getTransaction().begin();
        em.persist(customer);
        em.getTransaction().commit();
    }
    private static void nativeQuery(EntityManager em,String s){
        System.err.println("-----------" + s + "----------------");
        Query query = em.createNativeQuery(s);
        List list = query.getResultList();
        for (Object o : list) {
            if (o instanceof Object[]) {
                System.err.println(Arrays.toString((Object[])o));
            }else{
                System.err.println(o);
            }
        }
    }
}
